<!--*******************************************************************
* ActiveGrade Mobile
* Written by Sean Hickey for ActiveGrade, LLC
* 2011
********************************************************************-->
<!DOCTYPE html>
<html>
<head>
	<title>ActiveGrade Mobile</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="jquery.mobile-1.0b2.min.css" />
<style type="text/css">
.ag-gradebook-score-green,.ag-gradebook-score-yellow,.ag-gradebook-score-red
	{
	padding-left: 21px;
	background-repeat: no-repeat;
}

.ag-gradebook-score-green {
	background-image: url('/images/ag-status-green.png');
}

.ag-gradebook-score-yellow {
	background-image: url('/images/ag-status-yellow.png');
}

.ag-gradebook-score-red {
	background-image: url('/images/ag-status-red.png');
}
</style>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
	<script type="text/javascript" src="jquery.mobile-1.0b2.js"></script>
	<script type="text/javascript" src="jquery.validate.min.js"></script>
	<script type="text/javascript" src="ag-mobile.js"></script>
	<script type="text/javascript">
		
		if(!isLoggedIn()) {
			alert("You must be logged in to access this page");
			window.location.href='/';
		}
		
		var mainloaded = false;
		
		var userID = getCookie("userID");
		var pwd = getCookie("pwd");
		
		var orgs = {};
		var courses = {};
		var students = {};
		var standards = {};
		var policies = {};
		
		/*********************
		* jQuery Stuff
		**********************/
		
		$('#main').live('pageshow', function(event) {		//Workaround to show page loading on initial page load
			if(!mainloaded) {
				$.mobile.showPageLoadingMsg();
			}
		});
		
		$('.ui-page').live('pagecreate', function(event) {		//Add logout button to every page
			$(this).find('.ui-header').append('<a href="#" class="ui-btn-right" onclick="logout()">Logout</a>');
		});
		
		$('#main').live('pagecreate', function(event) {		//Initialize the main page
			if( !($('#courses').children().size() > 0) ) {
				getAllCourses(userID, pwd, function(data) {
					for (i in data) {
						if(data[i].isACourse) {
							courses[data[i].id] = new Course(data[i].name, data[i].evaluatedUserIds.length);
						}
						if (data[i].canBeGivenChildOrganizations){
							orgs[data[i].id] = new Org(data[i].name);
						}
					}
					$('#courses').append('<li data-role="list-divider">Folders</li>');
					for(i in orgs) {
						$('#courses').append('<li class="orglink" orgid="' + i + '"><span>' + escapeHtml(orgs[i].name) + '</span><ul data-role="listview" class="org' + i + '"></ul></li>');
					}
					$('#courses').append('<li data-role="list-divider">Classes</li>');
					for(i in courses) {
						$('#courses').append('<li class="courselink" courseid="' + i + '"><span>' + escapeHtml(courses[i].name) + '</span><span class="ui-li-count">' + courses[i].numstudents + '</span><ul data-role="listview" class="course' + i + '"></ul></li>');
					}
					$('#courses').listview('refresh');
					$.mobile.hidePageLoadingMsg();
					mainloaded = true;
				},
				function() {
					// Handle error
					alert("An error occured while loading. Make sure your internet connection is active and try again.");
					$.mobile.hidePageLoadingMsg();
				});
			}
		});
		
		$('.courselink').live('click', function() {
			$.mobile.showPageLoadingMsg();
			var currentcourse = $(this).attr('courseID');
			if( !(courses[currentcourse].students) ) {
				getStudentsForCourse(userID, pwd, currentcourse, function(data) {
					courses[currentcourse].students = {};
					var studentsArray = new Array();
					for(i in data) {
						if( !(students[data[i].id]) ) {
							students[data[i].id] = new Student(data[i].displayName);
						}
						courses[currentcourse].students[data[i].id] = students[data[i].id];
						studentsArray.push({name: data[i].displayName, id: data[i].id});
					}
					studentsArray.sort(function (a, b) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; else if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; else return 0; });
					for(i in studentsArray) {
						$('.course' + currentcourse).append('<li><a href="#assessment" class="studentlink" courseID="' + currentcourse + '" studentID="' + studentsArray[i].id + '">' + escapeHtml(studentsArray[i].name) + '</a></li>');
					}
					$('.course' + currentcourse).listview('refresh');
					$.mobile.hidePageLoadingMsg();
				},
				function() {
					// Handle error
					alert("An error occured while loading. Make sure your internet connection is active and try again.");
					$.mobile.hidePageLoadingMsg();
				});
			}
			else {
				$('.course' + currentcourse).empty();
				var studentsArray = new Array();
				for(i in courses[currentcourse].students) {
					studentsArray.push({name: courses[currentcourse].students[i].name, id: i});
				}
				studentsArray.sort(function (a, b) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; else if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; else return 0; });
				for (i in studentsArray) {
					$('.course' + currentcourse).append('<li><a href="#assessment" class="studentlink" courseID="' + currentcourse + '" studentID="' + studentsArray[i].id + '">' + escapeHtml(studentsArray[i].name) + '</a></li>');
				}
				$('.course' + currentcourse).listview('refresh');
				$.mobile.hidePageLoadingMsg();
			}
		});
		
		$('.orglink').live('click', function() {
			$.mobile.showPageLoadingMsg();
			var currentorg = $(this).attr('orgID');
			
			if( !(orgs[currentorg].suborgs) ) {
				getCoursesForOrganization(userID, pwd, currentorg, function(data) {
					orgs[currentorg].suborgs = {};
					orgs[currentorg].courses = {};
					for(i in data) {
						if( data[i].isACourse) {
							if( !(courses[data[i].id]) ) {
								courses[data[i].id] = new Course(data[i].name, data[i].evaluatedUserIds.length);
							}
							orgs[currentorg].courses[data[i].id] = courses[data[i].id];
						}
						if (data[i].canBeGivenChildOrganizations) {
							if( !(orgs[data[i].id]) ) {
								orgs[data[i].id] = new Org(data[i].name);
							}
							orgs[currentorg].suborgs[data[i].id] = orgs[data[i].id];
						}
					}
					loadOrgPage('.org' + currentorg, orgs[currentorg]);
					$.mobile.hidePageLoadingMsg();
				},
				function() {
					// Handle error
					alert("An error occured while loading. Make sure your internet connection is active and try again.");
					$.mobile.hidePageLoadingMsg();
				});
			}
			else {
				loadOrgPage('.org' + currentorg, orgs[currentorg]);
				$.mobile.hidePageLoadingMsg();
			}
		});
		
		$('.studentlink').live('click', function() {
			$.mobile.showPageLoadingMsg();
			var currentcourse = $(this).attr('courseid');
			var currentstudentid = $(this).attr('studentid');
			var currentstudent = $(this).html();
			$('#assessment').attr('courseid', currentcourse);
			$('#assessment').attr('studentid', currentstudentid);

			updateScoreField({isnumeric:true, min:0, max:4});
			if (!courses[currentcourse].standards) {
				//Standards have not been loaded yet
				getStandardsForCourse(userID, pwd, currentcourse, function(data) {
					courses[currentcourse].standards = {};
					for(i in data) {
						if ( !(standards[data[i].id]) ) {
							standards[data[i].id] = new Standard(data[i].name, data[i].gradingPolicyId, data[i].id);
						}
						courses[currentcourse].standards[data[i].id] = standards[data[i].id];
					}
					
					setupStandards(currentcourse, currentstudentid, currentstudent, standards);
				},
				function() {
					// Handle error
					alert("Unable to load course standards. Make sure your internet connection is active and try again.");
					$.mobile.hidePageLoadingMsg();
				});
			}
			else {	//Standards have already been loaded
				setupStandards(currentcourse, currentstudentid, currentstudent, courses[currentcourse].standards);
			}
			
		});
		
		$('#assessment').live('pagecreate', function(event) {
			$('#selectstandard').bind('change', function() {
				var chosenstandard = $(this).val();
				loadStandard(chosenstandard);
			});
			$('#assessmentname').bind('blur', function() {
				courses[$('#assessment').attr('courseid')].lastassessment = $(this).val();
			});
			$('#assessmentform').submit(function() {
				submitAssessment();
				return false;
			});
			
		});
		
		
		/*********************
		* Object Constructors
		**********************/
		
		function Org(orgname, suborgobject, coursesobject) {
			this.name = orgname;
			this.suborgs = suborgobject || null;
			this.courses = coursesobject || null;
		}
		
		function Course(coursename, numtotalstudents, studentsobject, standardsobject) {
			this.name = coursename;
			this.numstudents = numtotalstudents;
			this.students = studentsobject || null;
			this.standards = standardsobject || null;
		}
		
		function Student(studentname) {
			this.name = studentname;
		}
		
		function Standard(standardname, gradingpolicy, standardid) {
			this.name = standardname;
			this.policy = gradingpolicy || null;
			this.id = standardid;
		}
		
		function Policy(numericbool, minval, maxval, lettersarray, yellowlevel, greenlevel) {
			this.isnumeric = numericbool;
			this.min = minval;
			this.max = maxval;
			this.letters = lettersarray || null;
			this.yellow = yellowlevel;
			this.green = greenlevel;
		}
		
		
		/*********************
		* Other Functions
		**********************/
		
		function setupStandards(currentcourse, currentstudentid, currentstudent, standards) {

			var idToSelect = courses[currentcourse].laststandard || "";
			$('#assessmenttitle').html('Add Score for ' + currentstudent);
			$('#assessmentname').val(courses[currentcourse].lastassessment || 'Individual Assessment');
			$('#selectstandard').empty();
			$('#selectstandard').append('<option data-placeholder="true" disabled="true" value="-1">Choose Standard...</option>');
			for(i in courses[currentcourse].standards) {
				var selectString = i == idToSelect ? "selected='true'" : "";
				
				$('#selectstandard').append('<option value="' + i + '" ' + selectString + '>' + escapeHtml(standards[i].name) + '</option>');
			}

			$('#selectstandard').selectmenu('refresh');
			if(courses[currentcourse].laststandard) {
				loadStandard(courses[currentcourse].laststandard);
			} else {
			for (i in standards) {
				loadStandard(standards[i].id);
				return;
			}
			}
		}
		
		function innerLoadStandard(standardId, scale) {
			
			updateScoreField(scale);
			loadScoresForStandard(standardId, scale);
			$.mobile.hidePageLoadingMsg();
		}
		
		function loadStandard(standardId) {
			courses[$('#assessment').attr('courseid')].laststandard = standardId;
			if ( !(policies[standards[standardId].policy]) && standards[standardId].policy) {
				
				$.mobile.showPageLoadingMsg();
				$('#selectstandard').val(standardId);
				$('#selectstandard').selectmenu('refresh');
				getGradingPolicyForStandard(userID, pwd, standards[standardId].policy, function(data) {
					scale = data[0];
					if (!scale) {
						policies[standards[standardId].policy] = new Policy(true, 0, 4, null, 1, 3);
					} else 	if (scale.showNumbers) {
						policies[standards[standardId].policy] = new Policy(true, scale.minScore, scale.maxScore, null, scale.yellowLevel, scale.greenLevel);
					}
					else {
						var letters = new Array();
						for (i in scale.shortNames) {
							letters.push({name:scale.shortNames[i], value:scale.levelValues[i]});
						}
						policies[standards[standardId].policy] = new Policy(false, scale.minScore, scale.maxScore, letters, scale.yellowLevel, scale.greenLevel);
					}
					innerLoadStandard(standardId, policies[standards[standardId].policy]);
				},
				function () {
					// Handle error
					alert("Unable to load selected standard. Make sure your internet connection is active and try again.");
					$('#selectstandard').val(-1);
					$('#selectstandard').selectmenu('refresh');

					loadScoresForStandard(standardId, null);
				});
			} else if (standards[standardId].policy) {
				innerLoadStandard(standardId, policies[standards[standardId].policy]);
			} else {
				innerLoadStandard(standardId, new Policy(true, 0, 4, null, 1, 3));
			}
		}

		function getHtmlForScore(score, policy) {

			if (!policy) {
				policy = new Policy(true, 0, 4, null, 1, 3); //default policy
			}
			
			return getColorBlockFromScore(score, policy);
		}
		
		function getColorBlockFromScore(score, policy) {
			if (!score) {
				return "";
			}
			
			var style = "";
			if (score > policy.green) {
			  style = "ag-gradebook-score-green";
			} else if (score > policy.yellow) {
				style = "ag-gradebook-score-yellow";
			} else {
				style = "ag-gradebook-score-red";
			}
			
			return "<span class=\"" + style + "\">" + getTextFromScore(score, policy) + "</span>";
		}
		
		function getTextFromScore(score, policy) {
			//precondition: policy is not null
			if (policy.isnumeric) {
				return score;
			} else {
				for (i in policy.letters) {
					if (score >= policy.letters[i].value) {
						return escapeHtml(policy.letters[i].name);
					}
				}
				
				return "";
			}
		}

		function loadScoresForStandard(standardId, policy) {
			getPreviousScores(
					userID,
					pwd,
					$('#assessment').attr('studentid'),
					standardId,
					$('#assessment').attr('courseid'),
					function(data) {
						data.reverse();
						$('#scorehistory').empty();
						$('#scorehistory')
								.append(
										'<li data-role="list-divider">Previous Assessments</li>')
						for (i in data) {
							comment = "";
							if (data[i].comment) {
								comment = "<br/>" + escapeHtml(data[i].comment);
							}
							score = "";
							if (data[i].score) {
								score = getHtmlForScore(data[i].score, policy);
							}
							dateText = "";
							if (data[i] && data[i].dateMeasured) {
								d = new Date(data[i].dateMeasured);
								dateText = (d.getMonth()+1) + '/' + d.getDate();
								dateText = escapeHtml(dateText);
							}
							$('#scorehistory').append(
									"<li>" + dateText + ' ' + score + ' '
											+ comment + "<br/><br/></li>");
							$('#scorehistory').listview('refresh');
						}
					}, function() {
						//handle error retrieving previous scores
					});
		}

		function loadOrgPage(selector, orgobject) {
			$(selector).empty();
			$(selector).append('<li data-role="list-divider">Folders</li>');
			var folderArray = new Array();
			for (i in orgobject.suborgs) {
				folderArray.push({name: orgobject.suborgs[i].name, id: i})
			}
			folderArray.sort(function (a, b) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; else if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; else return 0; });
			for (var i in folderArray) {
				$(selector)
						.append(
								'<li class="orglink" orgid="' + folderArray[i].id + '"><span>'
										+ escapeHtml(folderArray[i].name)
										+ '</span><ul data-role="listview" class="org' + folderArray[i].id + '"></ul></li>');
			}
			$(selector).append('<li data-role="list-divider">Classes</li>');
			
			//need an array we can sort.  ERGH.
			var orgArray = new Array();
			for (i in orgobject.courses) {
				orgArray.push({name: orgobject.courses[i].name, id: i, numstudents: orgobject.courses[i].numstudents});
			}
			orgArray.sort(function (a, b) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; else if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; else return 0; });
			for (var i in orgArray) {
				$(selector)
						.append(
								'<li class="courselink" courseid="' + orgArray[i].id + '"><span>'
										+ escapeHtml(orgArray[i].name)
										+ '</span><span class="ui-li-count">'
										+ orgArray[i].numstudents
										+ '</span><ul data-role="listview" class="course' +  orgArray[i].id + '"></ul></li>');
			}
			$(selector).listview('refresh');
		}

		function clearAssessForm() {
			$('label.error').remove();
			$('#assessmentname').val('');
			$('#selectstandard').empty();
			$('#selectstandard').selectmenu('refresh');
			$('#comment').val('');
		}

		function updateScoreField(policy) {
			$('#scorefield').empty();
			$('#scorefield').append('<label for="score">Score:</label>');
			if (policy.isnumeric) {
				$('#scorefield')
						.append(
								'<input type="text" name="score" id="score" value="" class="assesselm" />');
				$('#score').textinput();
			} else {
				$('#scorefield')
						.append(
								'<select name="score" id="score" class="assesselm"></select>');
				$('#score')
						.append(
								'<option data-placeholder="true" value="-1">Choose Score...</option>');
				for (i in policy.letters) {
					$('#score').append(
							'<option value="' + policy.letters[i].value + '">'
									+ escapeHtml(policy.letters[i].name)
									+ '</option>');
				}
				$('#score').selectmenu();
			}
		}

		/********************************
		 * Form Validation and Submission
		 *********************************/

		 $.validator.addMethod("validscore", function (value, element) {
			 if (value == -1) {
				 return true;
			 }
			 
			 if ($('#selectstandard').val() != -1
						&& policies[standards[$('#selectstandard').val()].policy]) {
					scoremin = policies[standards[$('#selectstandard').val()].policy].min;
					scoremax = policies[standards[$('#selectstandard').val()].policy].max;
				} else {
					scoremin = 0;
					scoremax = 4;
				}
			 
			 return scoremin <= value && value <= scoremax;
		 }, "Invalid score");
		 
		$.validator.addMethod("lettersandspaces", function(value, element) {
			return this.optional(element) || /^[a-zA-Z0-9 ]+$/i.test(value);
		}, "Must be letters, numbers, and spaces only.");

		$.validator.addMethod("nominusone", function(value, element) {
			return this.optional(element) || value != -1
		}, "Please choose an option.");

		function submitAssessment() {
			var scoremin, scoremax;
			if ($('#selectstandard').val() != -1
					&& policies[standards[$('#selectstandard').val()].policy]) {
				scoremin = policies[standards[$('#selectstandard').val()].policy].min;
				scoremax = policies[standards[$('#selectstandard').val()].policy].max;
			} else {
				scoremin = 0;
				scoremax = 4;
			}
			$('#assessmentform').validate({
				onsubmit : false,
				rules : {
					assessmentname : {
						required : true
					},
					score : {
						required : false,
						number : true,
						validscore: true
					},
					selectstandard : {
						nominusone : true
					}

				},
				errorPlacement : function(error, element) {
					if (element.is('select')) {
						error.insertAfter(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
			if ($('#assessmentform').valid()) {
				$.mobile.loadingMessage = "submitting";
				$.mobile.showPageLoadingMsg();
				$('.assesselm').attr('disabled', 'disabled');
				submitScoreForStandard(
						userID,
						pwd,
						$('#assessmentname').val(),
						$('#score').val(),
						$('#assessment').attr('studentid'),
						$('#assessment').attr('courseid'),
						$('#selectstandard').val(),
						$('#comment').val(),
						function(data) {
							$.mobile.hidePageLoadingMsg();
							$.mobile.loadingMessage = "loading";
							alert("Assessment score successfully submitted");
							$('.assesselm').removeAttr('disabled');
							history.back();
						},
						function() {
							$.mobile.hidePageLoadingMsg();
							$.mobile.loadingMessage = "loading";
							alert("An error occurred while submitting the assessment score");
							$('.assesselm').removeAttr('disabled');
						});
			}
		}
	</script>
	
	<!-- Styling for validation errors -->
	<style type="text/css">
		label.error {
			margin: auto;
			color: red;
			display: block;
			width: 60%;
			text-align: right;
		}
	</style>
</head>
<body>
	<!-- MAIN COURSE PAGE -->
	<div data-role="page" id="main">
		<div data-role="header">
			<h1>ActiveGrade Mobile</h1>
		</div>
		<div data-role="content">
			<ul data-role="listview" id="courses">
			</ul>
		</div>
	</div>
	<!-- ADD STUDENT ASSESSMENT SCORE PAGE -->
	<div data-role="page" id="assessment">
		<div data-role="header">
			<h1 id="assessmenttitle">Add Score</h1>
		</div>
		<div data-role="content">
			<form id="assessmentform">
				<div data-role="fieldcontain">
					<label for="assessmentname">Assessment Name:</label>
					<input type="text" name="assessmentname" id="assessmentname" class="assesselm">
				</div>
				<div data-role="fieldcontain">
					<label for="selectstandard" class="select">Standard:</label>
					<select name="selectstandard" id="selectstandard" class="assesselm">
					</select>
				</div>
				<div data-role="fieldcontain" id="scorefield">
					<label for="score">Score:</label>
					<input type="text" name="score" id="score" value="" class="assesselm" />
				</div>
				<div data-role="fieldcontain">
					<label for="comment">Comment:</label>
					<textarea cols="40" rows="8" name="comment" id="comment" class="assesselm"></textarea>
				</div>
				<input type="submit" name="submit" value="Submit" class="assesselm" />
			</form>
			<br/>
			<ul data-role="listview" id="scorehistory"></ul></div>
		</div>
	</div>
</body>
</html>